package com.git.smp.controller;

import java.io.ByteArrayOutputStream;
import java.io.DataOutputStream;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.UnsupportedEncodingException;
import java.net.Socket;
import java.net.UnknownHostException;
import java.nio.charset.Charset;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletResponse;
import javax.websocket.DecodeException;

import org.apache.commons.codec.binary.Base64;
import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.DocumentHelper;
import org.dom4j.Element;
import org.dom4j.io.OutputFormat;
import org.dom4j.io.XMLWriter;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.json.JacksonJsonParser;
import org.springframework.http.ResponseEntity;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.http.converter.StringHttpMessageConverter;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.core.util.DefaultPrettyPrinter;
import com.fasterxml.jackson.databind.JsonMappingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.git.smp.cache.DataDictionaryCache;

import com.git.smp.core.PageRequest;
import com.git.smp.core.ResponseMessage;
import com.git.smp.dao.EsbEnvironmentMapper;
import com.git.smp.dao.LogDetailMapper;
import com.git.smp.dao.SmpEnvironmentMapper;
import com.git.smp.dao.SrvServiceLogDataMapper;
import com.git.smp.entity.ApplyEnvironment;
import com.git.smp.entity.DataDictionary;
import com.git.smp.entity.EsbEnvironment;
import com.git.smp.entity.HttpTransRequest;
import com.git.smp.entity.LogDetail;
import com.git.smp.entity.LogDetailKey;
import com.git.smp.entity.NetWork;
import com.git.smp.entity.SmpEnvironment;
import com.git.smp.entity.SocketTransRequest;
import com.git.smp.entity.SrvServiceLogDataExtend;
import com.git.smp.entity.SrvServiceLogDataWithBLOBs;
import com.git.smp.utils.EBCDICTransUtil;
import com.git.smp.utils.ExecuteShellUtil;
import com.git.smp.utils.HexBin;
import com.git.smp.utils.ObjectUtil;
import com.git.smp.utils.StringCompress;
import com.git.smp.utils.TransUtil;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.jcraft.jsch.JSchException;

@RestController
@RequestMapping("/trans")
public class TransController {
	
	Logger logger = LoggerFactory.getLogger(TransController.class);
	
	
	

	@RequestMapping("/socketTrans")
	public ResponseMessage<String> socketTrans(@RequestBody SocketTransRequest  socketTransRequest){
		ResponseMessage<String> responseMessage = new ResponseMessage<String>();
		responseMessage.setCode("0000");
		responseMessage.setMessage("查询成功！");
		OutputStream out = null;
		InputStream in = null;
		String responseMsg = "";
		try {
			Socket socket = new Socket(socketTransRequest.getIp(), Integer.parseInt(socketTransRequest.getPort()));
			byte[] request = socketTransRequest.getRequestBody().getBytes(DataDictionaryCache.getItemName("SMP0004", socketTransRequest.getCharSet()));
			byte[] pre = TransUtil.intTobyte((long)request.length+4, 4);
			 out =  socket.getOutputStream();
			 in =  socket.getInputStream();
			 out.write(pre);
			 out.write(request);
			 byte[] prelen = new byte[4];
			 in.read(prelen);
			 int responseLen = (int)TransUtil.byteToInt(prelen)-4;
			    byte[] responseBody = new byte[responseLen];
			    int offset = 0;
			    while(true) {
			    	int len = in.read(responseBody, offset, responseLen-offset);
			    	 offset+=len;
			    	 if(offset== responseLen) {
			    		 break;
			    	 }
			    }
			    responseMsg = new String(responseBody, DataDictionaryCache.getItemName("SMP0004", socketTransRequest.getCharSet()));
			    
		} catch (Exception e) {
			responseMessage.setCode("0001");
			responseMessage.setMessage(e.getMessage());
		} finally {
			try {
				in.close();
			} catch (IOException e) {
				e.printStackTrace();
			}
			try {
				out.close();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
		
		Document doc;
		try {
			doc = DocumentHelper.parseText(responseMsg);
			ByteArrayOutputStream arrayOutputStream = new ByteArrayOutputStream();
			OutputFormat format = OutputFormat.createPrettyPrint();
			format.setSuppressDeclaration(true);
			format.setNewLineAfterDeclaration(false);
			XMLWriter xmlWriter = new XMLWriter(arrayOutputStream,format);
			xmlWriter.write(doc);
			xmlWriter.close();
			responseMsg = arrayOutputStream.toString().replaceFirst("\n", "");
			
		} catch (Exception e) {
			
		}
		
		
		
		
		responseMessage.setExtend(responseMsg);
		logger.info(responseMessage.getMessage());
		return responseMessage;
	}
	
	
	
	@RequestMapping("/httpTrans")
	public ResponseMessage<String> httpTrans(@RequestBody HttpTransRequest  httpTransRequest){
		ResponseMessage<String> responseMessage = new ResponseMessage<String>();
		responseMessage.setCode("0000");
		responseMessage.setMessage("查询成功！");
		
		RestTemplate restTemplate = new RestTemplate();
		 List<HttpMessageConverter<?>>  messageConverters =restTemplate.getMessageConverters();
		
		 for(HttpMessageConverter httpMessageConverter :messageConverters) {
			 if(httpMessageConverter instanceof StringHttpMessageConverter) {
				 ((StringHttpMessageConverter)httpMessageConverter).setDefaultCharset(Charset.forName(DataDictionaryCache.getItemName("SMP0004", httpTransRequest.getCharSet())));
			 }
		 }
		 
		 
		 ResponseEntity<String>  responseEntity  = restTemplate.postForEntity(httpTransRequest.getUrl(), httpTransRequest.getRequestBody(), String.class);
		
		 //restTemplate.postForEntity(null, httpTransRequest, null);
		
			
			ObjectMapper mapper = new ObjectMapper();
			Map map;
			try {
				map = mapper.readValue(responseEntity.getBody(), Map.class);
				DefaultPrettyPrinter defaultPrettyPrinter = new DefaultPrettyPrinter();
				String msg = mapper.writer(defaultPrettyPrinter).writeValueAsString(map);
				responseMessage.setExtend(msg);
			} catch (Exception e) {
				responseMessage.setExtend(responseEntity.getBody());
			}
		logger.info(responseMessage.getMessage());
		return responseMessage;
	}
}
